<template>
  <el-dialog title="收货方地址设置"
             :visible="value"
             class="dialog-map-box"
             append-to-body
             :close-on-click-modal="false"
             width="900px"
             @update:visible="updateVisible($event)">
    <div>
      <div class="map-box">
        <div class="old-address">原地址：{{ oldAddress }}</div>
        <div class="line-box">
          <div class="address-hidden"
               :title="selectPoint.addr">新地址：{{ selectPoint.addr ||'' }}</div>
        </div>
        <div v-if="isSearchPoint || selectPointStatus"
             class="longitude">新经纬度：{{ `${selectPoint.lng || ''} , ${selectPoint.lat || ''}` }}</div>
        <div class="marks">
          标记定位点：
          <div class="marker"><img :src="oldMark"><span>原地址定位点</span></div>
          <div class="marker left-mark"><img :src="newMark"><span>点击设置新定位点</span></div>
          <el-button class="left-mark"
                     type="text"
                     @click="handleGoBack">返回原定位点</el-button>
        </div>
        <baidu-map ref="map"
                   v-loading="mapLoading"
                   :center="center"
                   :scroll-wheel-zoom="true"
                   class="map"
                   :zoom="zoom"
                   @ready="onMapReady"
                   @click="selectLocation">
          <bm-control :offset="{width: '10px', height: '10px'}">
            <bm-auto-complete v-model="keyword"
                              :sug-style="{zIndex: 99999}">
              <div class="search">
                <el-input v-model="keyword"
                          clearable
                          class="input-search"
                          size="medium"
                          placeholder="请输入输入地址搜索"></el-input>
                <div style=" height: 40px;">
                  <el-button type="primary"
                             size="small"
                             @click="searchLocation(keyword)">搜索</el-button>
                </div>
              </div>
            </bm-auto-complete>
          </bm-control>
          <!-- 原地址标注 -->
          <bm-marker :position="defaultPoint"
                     :icon="{url: oldMark, size: {width: 32, height: 32}}"></bm-marker>
          <!-- 搜索标注 -->
          <bm-marker v-if="isSearchPoint"
                     :position="searchPoint"
                     :icon="{url: newMark, size: {width: 32, height: 32}}">
          </bm-marker>
          <!-- 点击标注 -->
          <bm-marker v-if="selectPointStatus"
                     :position="selectPoint"
                     :icon="{url: newMark, size: {width: 32, height: 32}}"></bm-marker>
        </baidu-map>
      </div>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 :disabled="!selectPointStatus"
                 @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import newMark from '@/static/images/new.png'
import oldMark from '@/static/images/old.png'
import _ from "lodash";
import { basic } from "@service";

export default {
  name: 'MapModule',
  inject: ["$table"],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    preset: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      newMark,
      oldMark,
      center: {
        lng: '',
        lat: ''
      },
      show: true,
      zoom: 15,
      selectPoint: {
        lng: '',
        lat: '',
        addr: ''
      },
      defaultPoint: {
        lng: '',
        lat: ''
      },
      searchPoint: {
        lng: '',
        lat: ''
      },
      keyword: '',
      isSearchPoint: false,
      details: {},
      map: null,
      setTime: null,
      mapLoading: true,
      loading: false,
      subDisabled: true,
      selectPointStatus: false
    }
  },
  computed: {
    oldAddress () {
      return `${this.details?.province || ''}${this.details?.city || ''}${this.details?.district || ''}${this.details?.address || ''}`
    },
    filterData () {
      const { addressId } = this.details
      return {
        addressId: addressId,
        location: `${this.selectPoint?.lng},${this.selectPoint?.lat}`
      }
    },
    // subDisabled () {
    //   return !this.selectPoint?.addr
    // },
    clearObject () {
      return obj => Object.keys(obj).forEach(key => delete obj[key]);
    }
  },
  watch: {
    value () {
      if (this.value) {
        this.init()
      }
    }
  },
  created () {

  },
  beforeDestroy () {
    if (this.setTime) {
      clearInterval(this.setTime)
      this.setTime = null
    }
  },
  methods: {
    async loadMap () {
      const response = await basic.getReceivingAddress(this.preset.addressId)
      if (response?.code === 0) {
        this.details = response.data
      }
    },
    init () {
      this.selectPointStatus = false
      this.isSearchPoint = false
      this.keyword = ""
      this.clearObject(this.selectPoint)
      this.loadMap()
      if (this.map) {
        this.onMapReady({ map: this.map })
      }
    },
    handleClose () {
      this.$emit("input", false);
    },
    updateVisible ($event) {
      this.$emit('input', $event)
    },
    async searchLocation (keyword) {
      try {
        const point = await this.getPointByAddress(keyword);
        point.addr = keyword;
        this.selectPoint = point;
        this.searchPoint = point;
        this.center = point
        this.zoom = 15
        this.isSearchPoint = true
      } catch (error) {
        console.error(error);
      }
    },
    selectLocation (event) {
      this.selectPointStatus = true
      const point = new BMap.Point(event.point.lng, event.point.lat);
      const geocoder = new BMap.Geocoder();
      geocoder.getLocation(point, (result) => {
        if (result) {
          const addressTitle = result?.surroundingPois[0]?.address + result?.surroundingPois[0]?.title
          this.selectPoint = {
            lng: point.lng,
            lat: point.lat,
            addr: result?.surroundingPois?.length > 0 ? addressTitle : result?.address
          };
          this.isSearchPoint = false
        } else {
          alert('地址解析失败，请重新选择！');
        }
      }, '全国');
    },
    submit: _.debounce(async function () {    // 触发事件
      this.loading = true
      const response = await basic.receivingAddress(this.preset.addressId, this.filterData)
      if (response.code === 0) {
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.loading = false
        this.$emit("input", false);
        this.$table.search();
      }
    }, 400),
    async handleGoBack () {
      try {
        const { lon, lat } = this.details
        const point = {
          lng: lon,
          lat: lat,
          addr: this.oldAddress
        };
        this.selectPoint = point
        this.searchPoint = point
        this.center = point
        this.zoom = 15
        this.isSearchPoint = true
      } catch (error) {
        console.error(error);
      }
    },
    // 根据地址名称获取经纬度坐标
    getPointByAddress (address) {
      const myGeo = new BMap.Geocoder();
      return new Promise((resolve, reject) => {
        myGeo.getPoint(address, (point) => {
          if (point) {
            resolve(point);
          } else {
            reject('地理编码失败');
          }
        }, '全国');
      });
    },
    async onMapReady ({ map }) {
      this.map = map
      map.setDefaultCursor("crosshair");
      try {
        this.setTime = setTimeout(() => {
          const { lon, lat } = this.details
          const point = new BMap.Point(lon, lat);
          this.defaultPoint.lng = lon
          this.defaultPoint.lat = lat
          this.center = this.defaultPoint
          map.centerAndZoom(point, 15);
          this.mapLoading = false
        }, 200)
      } catch (error) {
        console.error(error);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-map-box ::v-deep .el-dialog__body {
  padding: 0;
}
.old-address,
.longitude,
.line-box,
.marks {
  padding: 10px 20px 0px 20px;
}
.map >>> .BMap_cpyCtrl {
  display: none !important;
}
.map >>> .anchorBL {
  display: none !important;
}
.map {
  width: 100%;
  height: 400px;
}
.map-box {
  font-size: 16px;
  color: #333;
  line-height: 40px;
}

.line-box {
  font-weight: bold;
  display: flex;
  /* justify-content: space-between; */
}
.search {
  display: flex;
  height: 36px;
  padding: 7px;
}
.input-search {
  width: 300px;
}
.marks {
  display: flex;
}
.marker {
  display: flex;
  align-items: center;
}
.marker img {
  width: 28px;
  height: 28px;
  margin-right: 5px;
}
.left-mark {
  padding-left: 100px;
}
.foot-button {
  text-align: right;
}
.address-hidden {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>